package com.j.lemon.learn.thread.produc1consum;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author lijunjun
 * @Date 2019-04-22 15:33
 * @Description  Reentrantlock的lock + Condition的await 和 signal 实现的传统的生产者消费者模式  ，两个线程交替对一个资源类进行加减
 */
public class TraditionalDemo3 {
    public static void main(String[] args) {
        ShareData3 shareData = new ShareData3();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    shareData.add();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();


        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    shareData.delete();
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();
    }
}

class ShareData3{

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    int num = 0;

    public void add() throws InterruptedException {
        lock.lock();
        try{
            while(num !=0){
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"+1");
            condition.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    public void delete() throws InterruptedException {
        lock.lock();
        try{
            while(num ==0){
                condition.await();
            }
            num--;
            System.out.println(Thread.currentThread().getName()+"-1");
            condition.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

}

